package com.laikan.reader.bookreader.activity;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.laikan.library.components.BasicApplication;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.helpers.BasicEvent;
import com.laikan.reader.R;
import com.laikan.reader.apirequester.CommentDetailRequester;
import com.laikan.reader.core.adapter.ReplyAdatper;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.BaseListDataBean;
import com.laikan.reader.core.bean.CommentBean;
import com.laikan.reader.core.bean.ReplyBean;
import com.laikan.reader.core.events.LaiKanEvent;
import com.laikan.reader.core.utils.ActivityUitl;
import com.laikan.reader.core.utils.LoadingDialog;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.core.view.CircleProgressBar;
import com.laikan.reader.core.view.ProgressBar_Modern;
import com.laikan.reader.core.view.SnackBarNotice;
import com.laikan.reader.core.view.TouchSwipeRefreshLayout;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

/**
 * 评论详情页面
 *
 * @author wxl
 */
@SuppressLint ("HandlerLeak")
public class CommentDetailActivity extends BasicActivity {

    private int total;// 返回的数据总数
    private ListView comment_detail_list;
    @SuppressWarnings ("rawtypes")
    private CommentBean headData;
    private ArrayList<ReplyBean> mReplyDataList;
    private ReplyAdatper mAdapter;
    private String replyId, comment;
    private Boolean commentJing;
    private EditText comment_edit;
    private Button send_btn;
    private View head_view;
    private ImageView back_tv;
    private RelativeLayout back_layout, rl_clicktosupport;
    private LoadingDialog mloadingDialog;
    private ImageView iv_clicktosupport;

    private int mCurrentPage = 1;
    private int END_LIST_PAGE = -1;
    private long mLoadDataInternalTime;
    private long mLoadDelayInternalTime;
    private ProgressBar_Modern mModernLoadProgressBar;
    private TouchSwipeRefreshLayout mComment_SwipeRefresh;
    private HashSet mReplyIdList = new HashSet();
    private boolean isSendReplySeuuces = false;
    private RelativeLayout common_loaddata_notice;
    private TextView common_prompt_content, common_refresh_net;
    private RelativeLayout bottom_layout;
    private CircleProgressBar circleProgressBar;
    private View lk_comment_foot_view;
    private boolean mIsClickToSupportSuccess = true;
    private ImageView common_prompt_image;

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void assignViews() {
        setContentView(R.layout.lk_comment_detail);
        mComment_SwipeRefresh = (TouchSwipeRefreshLayout)findViewById(R.id.common_swiperefresh);
        mComment_SwipeRefresh.setColorSchemeResources(R.color.C_66ccdd);
        comment_detail_list = (ListView)findViewById(R.id.comment_detail_listview);
        comment_edit = (EditText)findViewById(R.id.comment_edit);
        send_btn = (Button)findViewById(R.id.send_btn);
        head_view = View.inflate(mContext, R.layout.lk_comment_head, null); // 头布局
        lk_comment_foot_view = View.inflate(mContext, R.layout.lk_comment_foot_view, null); // 脚布局
        comment_detail_list.addHeaderView(head_view);
        comment_detail_list.addFooterView(lk_comment_foot_view);
        back_tv = (ImageView)findViewById(R.id.iv_back);
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
        mModernLoadProgressBar = (ProgressBar_Modern)findViewById(R.id.progressbar_modern);
        mComment_SwipeRefresh.setChildView(comment_detail_list);
        common_loaddata_notice = (RelativeLayout)findViewById(R.id.common_loaddata_notice);
        common_prompt_content = (TextView)findViewById(R.id.common_prompt_content);
        common_refresh_net = (TextView)findViewById(R.id.common_refresh_net);
        common_prompt_image = (ImageView)findViewById(R.id.common_prompt_image);
        circleProgressBar = (CircleProgressBar)findViewById(R.id.comon_bgbar_loading);
        bottom_layout = (RelativeLayout)findViewById(R.id.bottom_layout);
    }

    @Override
    protected void initData() {
        lk_comment_foot_view.setVisibility(View.GONE);
        openEventBus();
        mloadingDialog = new LoadingDialog(mContext);
        BitmapDrawable drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        back_tv.setImageDrawable(drawable_back_tv);
        mReplyDataList = new ArrayList<>();
        mAdapter = new ReplyAdatper(mContext, mReplyDataList);
        replyId = getIntent().getStringExtra("replyId");
        commentJing = getIntent().getBooleanExtra("commentjing", false);
        comment_detail_list.setAdapter(mAdapter);
        mComment_SwipeRefresh.setEnabled(false);
        requestNetData();

    }

    private void requestNetData() {
        if (ActivityUitl.isNetworkAvailable(this)) {
            showDialog();
            CommentDetailRequester.getReplayList(mCurrentPage, replyId, mComment_SwipeRefresh);
        }else {
            common_prompt_content.setText(R.string.laikan_network_anomaly);
            changePageStatus(false);
        }
    }
    @Override
    protected void parseEvent(BasicEvent event) {
        switch (event.getEventID()) {
            case LaiKanEvent.EVENT_ID_GET_REPLY_LIST:
                dismissDialog();
                changePageStatus(true);
                BaseDataBean<CommentBean<ReplyBean>> result = (BaseDataBean<CommentBean<ReplyBean>>)event.getElves();
                headData = result.getData();
                mAdapter.setDatas(updateListData(result.getData().getReplyList()));

                total = Integer.parseInt(PublicUtil.isNum(result.getData().getTotal()));
                if (isSendReplySeuuces) {
                    refredhReplyNumber(total);
                    isSendReplySeuuces = false;
                }
                getCurrentPage(result.getData().getTotal());
                setView();
                showLayout();
                break;
            case LaiKanEvent.EVENT_ID_SEND_REPLY:
                mCurrentPage = 1;
                isSendReplySeuuces = true;
                CommentDetailRequester.getReplayList(mCurrentPage, replyId, mComment_SwipeRefresh);
                comment_edit.setText("");
                break;
            case LaiKanEvent.EVENT_ID_GET_MORE_REPLY:
                BaseDataBean<BaseListDataBean<ReplyBean>> result1 = (BaseDataBean<BaseListDataBean<ReplyBean>>)event.getElves();
                mAdapter.setDatas(loadMoreData(result1.getData().getReplyList()));
                getCurrentPage(result1.getData().getTotal());
                closeLoadMoreView(System.currentTimeMillis());
                break;
            case LaiKanEvent.EVENT_ID_COMMENT_NOTIC:
                dismissDialog();
                if (event.getEventAction().equals("netfailed")) {
                    common_prompt_content.setText(R.string.laikan_network_anomaly);
                }else if(event.getEventAction().equals("datafailed")){
                    common_prompt_content.setText(R.string.laikan_data_load_failed);
                }else if(event.getEventAction().equals("userClose")){
                    common_prompt_content.setText(R.string.deleted_comment);
                    common_refresh_net.setVisibility(View.GONE);
                    common_prompt_image.setImageDrawable(getResources().getDrawable(R.drawable.del_comment));
                }
                closeDelayLoading(System.currentTimeMillis());
                break;
            case LaiKanEvent.EVENT_ID_SHOW_NOTICE:
                SnackBarNotice.customSnackbarShow(comment_detail_list,event.getEventAction());
                closeLoadMoreView(System.currentTimeMillis());
                break;
            case LaiKanEvent.EVENT_ID_FOCUS_REFRESH_REPLY_NUMBER:
                mIsClickToSupportSuccess = true;
                break;
            default:
                break;
        }
    }
    private void showLayout(){
        bottom_layout.setVisibility(View.VISIBLE);
        mComment_SwipeRefresh.setVisibility(View.VISIBLE);
        common_loaddata_notice.setVisibility(View.GONE);
    }
    /**
     * 数据处理，ui展示
     */
    private void setView() {
        com.facebook.drawee.view.SimpleDraweeView person_img = (com.facebook.drawee.view.SimpleDraweeView)head_view.findViewById(R.id.head_reviewer_img);
        TextView username = (TextView)head_view.findViewById(R.id.head_reviewer_name);
        ImageView comment_image_jing = (ImageView)head_view.findViewById(R.id.comment_imge_jing);
        //        comment_image_jing.setVisibility(View.GONE);
        TextView comment_time = (TextView)head_view.findViewById(R.id.head_comment_time);
        TextView comment_title = (TextView)head_view.findViewById(R.id.comment_title);
        TextView comment_content = (TextView)head_view.findViewById(R.id.head_comment_content);
//        //看点评论列表添加头部点赞功能
//        if (getIntent() != null && "from_focus_comment".equals(getIntent().getStringExtra("from"))) {
//            rl_clicktosupport = (RelativeLayout)head_view.findViewById(R.id.rl_clicktosupport);
//            rl_clicktosupport.setVisibility(View.VISIBLE);
//            rl_clicktosupport.setOnClickListener(this);
//            TextView tv_clicktosupport = (TextView)head_view.findViewById(R.id.tv_clicktosupport);
//            iv_clicktosupport = (ImageView)head_view.findViewById(R.id.iv_clicktosupport);
//            // TODO: 2016/11/3 新接口提供后，修改点赞初始化逻辑
//            if (true) {
//                iv_clicktosupport.setImageDrawable(new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(LaikanApplication.getInstance(), R.drawable
//                    .iv_click_to_support), Color
//                    .parseColor("#66ccdd"))));
//                tv_clicktosupport.setText("" + 0);
//            }else {
//                iv_clicktosupport.setImageDrawable(new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(LaikanApplication.getInstance(), R.drawable
//                    .iv_click_to_support), Color
//                    .parseColor("#999999"))));
//                tv_clicktosupport.setText("" + 0);
//            }
//        }

        person_img.setVisibility(View.VISIBLE);
        person_img.setImageURI(Uri.parse(headData.getUserIcon()));
        username.setText(headData.getUserName());
        if (TextUtils.isEmpty(headData.getName())) {
            comment_title.setVisibility(View.GONE);
        }else {
            comment_title.setVisibility(View.VISIBLE);
            comment_title.setText(headData.getName());
        }
        comment_content.setText(headData.getContent());
        comment_time.setText(headData.getCreateTime());
        if (commentJing) {
            comment_image_jing.setVisibility(View.GONE);
        }else {
            comment_image_jing.setVisibility(View.GONE);
        }
        View view_huifu = head_view.findViewById(R.id.view_huifu);
        view_huifu.setVisibility(View.VISIBLE);
    }

    private void refredhReplyNumber(int totalReply) {
        LaiKanEvent event = LaiKanEvent.getInstance();
//        if (getIntent() != null && "from_focus_comment".equals(getIntent().getStringExtra("from"))) {
//            event.setEventID(LaiKanEvent.EVENT_ID_FOCUS_REFRESH_REPLY_NUMBER);
//        }else {
            event.setEventID(LaiKanEvent.EVENT_ID_BOOK_REFRESH_REPLY_NUMBER);
//        }
        Map<String, Object> mapEvent = new HashMap<>();
        mapEvent.put("totalreply", totalReply + "");
        mapEvent.put("replyId", replyId);
        mapEvent.put("totallikecount", null);
        mapEvent.put("isFavor", false);
        BasicApplication.postEvent(event.setEventMap(mapEvent));
    }

    private void getCurrentPage(String totalSize) {
        int PAGE_LIMIT_SIZE = 10;
        mCurrentPage = mReplyDataList.size() / PAGE_LIMIT_SIZE + 1;
        total = Integer.parseInt(PublicUtil.isNum(totalSize));
        if (mReplyDataList.size() >= total) {
            mCurrentPage = END_LIST_PAGE;
        }
    }

    private ArrayList<ReplyBean> updateListData(ArrayList<ReplyBean> list) {
        ArrayList<ReplyBean> refreshList = new ArrayList<>();
        for (ReplyBean aList : list) {
            if (!mReplyIdList.contains(aList.getReplyId())) {
                mReplyIdList.add(aList.getReplyId());
                refreshList.add(aList);
            }
        }
        refreshList.addAll(mReplyDataList);
        mReplyDataList.clear();
        mReplyDataList.addAll(refreshList);
        refreshList.clear();
        return mReplyDataList;
    }

    private ArrayList<ReplyBean> loadMoreData(ArrayList<ReplyBean> list) {
        for (ReplyBean aList : list) {
//            if (!mReplyIdList.contains(aList.getReplyId())) {
                mReplyIdList.add(aList.getReplyId());
                mReplyDataList.add(aList);
//            }
        }
        return mReplyDataList;
    }

    @Override
    protected void setListener() {
        back_layout.setOnClickListener(this);
        send_btn.setOnClickListener(this);
        common_refresh_net.setOnClickListener(this);
        comment_edit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                InputMethodManager imm = ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE));
                if (!hasFocus) {
                    imm.hideSoftInputFromWindow(comment_edit.getWindowToken(), 0);
                }
            }
        });
        comment_edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                comment = comment_edit.getText().toString();
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    send_btn.setTextColor(getResources().getColor(R.color.C_66ccdd));
                }else {
                    send_btn.setTextColor(getResources().getColor(R.color.C_333333));
                }
            }
        });

        // 下拉刷新 上拉加载
        //use TouchSwipeRefreshLayout OnRefreshListener
        mComment_SwipeRefresh.setOnRefreshListener(new TouchSwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mComment_SwipeRefresh.setLoading(false);
                mCurrentPage = 1;
                CommentDetailRequester.getReplayList(mCurrentPage, replyId, mComment_SwipeRefresh);

            }
        });

        mComment_SwipeRefresh.setOnLoadListener(new TouchSwipeRefreshLayout.OnLoadListener() {
            @Override
            public void onLoad() {
                mComment_SwipeRefresh.setRefreshing(false);
                if (!ActivityUitl.isNetworkAvailable(mContext)) {
                    SnackBarNotice.customSnackbarShow(comment_detail_list, R.string.laikan_network_anomaly);
                    mComment_SwipeRefresh.setLoading(false);
                }else {
                    if (END_LIST_PAGE == mCurrentPage) {
                        lk_comment_foot_view.setVisibility(View.VISIBLE);
                        //SnackBarNotice.customSnackbarShow(comment_detail_list, R.string.fw_data_all_load_done);
                        mComment_SwipeRefresh.setLoading(false);
                        closeLoadMoreView(System.currentTimeMillis());
                    }else {
                        lk_comment_foot_view.setVisibility(View.GONE);
                        mModernLoadProgressBar.setVisibility(View.VISIBLE);
                        mLoadDataInternalTime = System.currentTimeMillis() + 2000;
                        CommentDetailRequester.loadMoreReplayDate(mCurrentPage, replyId, mComment_SwipeRefresh);
                    }
                }
            }
        });
    }

    private void closeLoadMoreView(long currenttime) {
        if (currenttime < mLoadDataInternalTime) {
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    mModernLoadProgressBar.setVisibility(View.GONE);
                }
            }, 1000);
        }else {
            mModernLoadProgressBar.setVisibility(View.GONE);
        }
    }

    public void closeDelayLoading(long currenttime) {
        if (currenttime < mLoadDelayInternalTime) {
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    changePageStatus(false);
                }
            }, 1000);
        }else {
            changePageStatus(false);
        }
    }

    private void changePageStatus(boolean isLoadSucess) {
        common_refresh_net.setOnClickListener(CommentDetailActivity.this);
        if (isLoadSucess) {
            bottom_layout.setVisibility(View.VISIBLE);
            mComment_SwipeRefresh.setVisibility(View.VISIBLE);
            common_loaddata_notice.setVisibility(View.GONE);
            circleProgressBar.setVisibility(View.INVISIBLE);
        }else {
            bottom_layout.setVisibility(View.GONE);
            mComment_SwipeRefresh.setVisibility(View.GONE);
            common_loaddata_notice.setVisibility(View.VISIBLE);
            circleProgressBar.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send_btn:
                comment = comment_edit.getText().toString().trim();
                CommentDetailRequester.sendReply(comment, replyId, mloadingDialog);
                break;
            case R.id.back_layout:
                comment_edit.clearFocus();
                finish();
                break;
            case R.id.common_refresh_net:
                common_refresh_net.setOnClickListener(null);
                circleProgressBar.setVisibility(View.VISIBLE);
                mLoadDelayInternalTime = System.currentTimeMillis() + 2000;
                mCurrentPage = 1;
                if (ActivityUitl.isNetworkAvailable(this)) {
                    CommentDetailRequester.getReplayList(mCurrentPage, replyId, mComment_SwipeRefresh);
                }else {
                    common_prompt_content.setText(R.string.laikan_network_anomaly);
                    closeDelayLoading(System.currentTimeMillis());
                }
                break;
//            case R.id.rl_clicktosupport:
//                if (BookFileUtils.isNoLogin()) {
//                    Intent intent = new Intent(mContext, LoginActivity.class);
//                    startActivity(intent);
//                }else if (!ActivityUitl.isNetworkAvailable(CommentDetailActivity.this)) {
//                    SnackBarNotice.customSnackbarShow(bottom_layout, R.string.laikan_network_anomaly);
//                }else {
//                    if (mIsClickToSupportSuccess) {
//                        mIsClickToSupportSuccess = false;
//                        BookDesRequester.clickToSupport(rl_clicktosupport, headData.getId(), LaiKanEvent.EVENT_ID_FOCUS_REFRESH_REPLY_NUMBER);
//                    }
//                }
//                break;
            default:
                break;
        }
    }
}
